﻿using ClosedXML.Excel;
using DocumentFormat.OpenXml.Drawing;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace JaasExportExcel.Views
{
    public partial class HomePage : UserControl
    {
        private List<MyData> _data = new();

        public HomePage()
        {
            InitializeComponent();
        }

        private async void LoadMore_Click(object sender, RoutedEventArgs e)
        {
            string baseUrl = "http://localhost:8080/derivedData/getRawDataList";
            string startTime = "2025-07-06";
            string endTime = "2025-07-06";
            short houseId = 1;

            var requestPayload = new
            {
                startTime,
                endTime,
                houseId
            };

            try
            {
                using var client = new HttpClient();

                string json = JsonSerializer.Serialize(requestPayload);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(baseUrl, content);
                response.EnsureSuccessStatusCode();

                string resultJson = await response.Content.ReadAsStringAsync();

                // 反序列化为 List<MyData>（你也可以先反序列化为 List<Dictionary<string, object>>）
                var result = JsonSerializer.Deserialize<List<MyData>>(resultJson, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                _data = result ?? new List<MyData>();
                DataList.ItemsSource = _data;
            }
            catch (Exception ex)
            {
                MessageBox.Show("接口请求失败：" + ex.Message);
            }
        }

        private void ExportExcel_Click(object sender, RoutedEventArgs e)
        {
            if (_data == null || _data.Count == 0)
            {
                MessageBox.Show("没有数据可导出！");
                return;
            }

            var dialog = new Microsoft.Win32.SaveFileDialog
            {
                FileName = "导出数据",
                DefaultExt = ".xlsx",
                Filter = "Excel 文件 (*.xlsx)|*.xlsx"
            };

            if (dialog.ShowDialog() == true)
            {
                using var wb = new XLWorkbook();
                var ws = wb.Worksheets.Add("数据");

                ws.Cell(1, 1).Value = "ID";
                ws.Cell(1, 2).Value = "名称";
                //ws.Cell(1, 3).Value = "时间";
                ws.Cell(1, 3).Value = "Ts";

                for (int i = 0; i < _data.Count; i++)
                {
                    ws.Cell(i + 2, 1).Value = _data[i].Id;
                    ws.Cell(i + 2, 2).Value = _data[i].Name;
                    //ws.Cell(i + 2, 3).Value = _data[i].Time;
                    ws.Cell(i + 2, 3).Value = _data[i].Ts;
                }

                wb.SaveAs(dialog.FileName);
                MessageBox.Show("导出成功！");
            }
        }
    }

    public class MyData
    {
        private string? ts;

        public int Id { get; set; }
        public string Name { get; set; } = "";
        //public DateTime Time { get; set; }
        public string? Ts { get => ts; set => ts = value; }
    }
}